package com.hontech.libratest.utils


fun Byte.toUInt8() = this.toInt() and 0xFF

fun ByteArray.toUInt8(index: Int) = this[index].toUInt8()

fun ByteArray.toUInt16(index: Int): Int {
    return (this[index].toUInt8() shl 8) + this[index + 1].toUInt8()
}

fun ByteArray.toUInt32(index: Int): Int {
    return (this[index].toUInt8() shl 24) +
            (this[index + 1].toUInt8() shl 16) +
            (this[index + 2].toUInt8() shl 8) +
            this[index + 3].toUInt8()
}

private val HexList = charArrayOf(
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'A', 'B',
    'C', 'D', 'E', 'F'
)

fun ByteArray.toHexString(): String {
    val len = this.size
    val chars = CharArray(len * 3)
    for (i in 0 until len) {
        val value = this[i].toUInt8()
        val h = value shr 4
        val l = value and 0x0F
        chars[i * 3 + 0] = HexList[h]
        chars[i * 3 + 1] = HexList[l]
        chars[i * 3 + 2] = ' '
    }
    return String(chars)
}

fun Int.toHexStr2(): String {
    val chars = CharArray(2)
    val h = (this shr 4) and 0x0F
    val l = this and 0x0F
    chars[0] = HexList[h]
    chars[1] = HexList[l]
    return String(chars)
}

fun Int.toHexStr4(): String {
    val chars = CharArray(4)
    val h0 = (this shr 12) and 0x0F
    val h1 = (this shr 8) and 0x0F
    val h2 = (this shr 4) and 0x0F
    val h3 = this and 0x0F
    chars[0] = HexList[h0]
    chars[1] = HexList[h1]
    chars[2] = HexList[h2]
    chars[3] = HexList[h3]
    return String(chars)
}

fun ByteArray.encodeUInt8(index: Int, value: Int) {
    this[index] = value.toByte()
}

fun ByteArray.encodeUInt16(index: Int, value: Int) {
    this[index] = (value shr 8).toByte()
    this[index + 1] = value.toByte()
}

fun ByteArray.encodeUInt32(index: Int, value: Int) {
    this[index] = (value shr 24).toByte()
    this[index + 1] = (value shr 16).toByte()
    this[index + 2] = (value shr 8).toByte()
    this[index + 3] = value.toByte()
}

fun ByteArray.xorSum(index: Int, size: Int): Int {
    var s = 0
    for (i in index until (index + size)) {
        s = s xor this[i].toUInt8()
    }
    return s
}

fun Int.isBitSet(bit: Int): Boolean {
    return (this and (0x01 shl bit)) != 0
}

fun Int.unsignedInt16(): Int {
    var value = this
    if (this < 0) {
        value = 0x10000 - (-this)
    }
    return value
}

fun Int.signedInt16(): Int {
    if ((this and 0x8000) != 0) {
        return -(0x10000 - this)
    }
    return this
}
















